<template>
  <div>
    <el-button
      type="primary"
      icon="el-icon-plus"
      @click="showAddOrUpdateTrademark(true)"
      >添加</el-button
    >

    <template>
      <el-table :data="trademark" style="width: 100%" v-loading="loading">
        <el-table-column label="序号" width="200" type="index">
        </el-table-column>
        <el-table-column prop="tmName" label="品牌名称"> </el-table-column>
        <el-table-column prop="logoUrl" label="品牌LOGO">
          <template v-slot="{ row }">
            <img :src="row.logoUrl" style="width: 100px" />
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <!-- 用template插槽能获取整行的数据 row 当前行所有的数据 -->
          <template v-slot="{ row }">
            <el-button
              type="warning"
              icon="el-icon-editor"
              @click="showAddOrUpdateTrademark(false, row)"
              >修改</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              @click="delTrademark(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </template>

    <el-dialog
      :title="`${isAddtrademark ? '添加' : '修改'}品牌`"
      :visible.sync="dialogVisible"
      width="30%"
    >
      <!-- 表单 -->
      <el-form ref="form" :model="tradeForm" label-width="80px" :rules="rules">
        <el-form-item label="品牌名称" prop="tmName">
          <el-input v-model="tradeForm.tmName" class="brand-input"> </el-input>
        </el-form-item>

        <!-- 上传图片组件   当前图片发送地址一定要是绝对路径
          /admin/product/fileUpload这样写前面会自动补充当前服务器的域名端口号 -->
        <el-form-item label="品牌LOGO" prop="logoUrl" label-width="91px">
          <el-upload
            class="avatar-uploader"
            action="http://39.98.123.211/admin/product/fileUpload"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :on-success="handleAvatarSuccess"
          >
            <img
              v-if="tradeForm.logoUrl"
              :src="tradeForm.logoUrl"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <span>只能上传jpg/png文件，且不超过500kb</span>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer" style="center">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOrUpdateTrademark">
          确 定</el-button
        >
      </span>
    </el-dialog>

    <el-pagination
      style="text-align: right; margin-top: 15px"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[3, 6, 9]"
      :page-size="pageSize"
      layout="  prev, pager, next, jumper,sizes,total"
      :total="total"
    >
    </el-pagination>
  </div>
</template>

<script>
import {
  reqGetTrademark,
  reqAddTrademark,
  reqUpdateTrademark,
  reqDeleteTrademark,
} from "@/api/getTrademark";

export default {
  name: "Trademask",

  data() {
    return {
      trademark: [],
      currentPage: 1,
      total: 30,
      pageSize: 3,
      dialogVisible: false,
      tradeForm: {
        tmName: "",
        logoUrl: "",
      },
      isAddtrademark: false,
      loading: false,
      //表单校验规则
      rules: {
        tmName: [
          /* { required: true, message: "请输入品牌名称", trigger: "blur" },
          { min: 2, max: 6, message: "长度在 2 到 8 个字符", trigger: "blur" }, */
          //required 是配合message用的 否则单纯用就是添加个* 号
          { required: true, validator: this.validator, trigger: "blur" },
        ],
        logoUrl: [
          { required: true, message: "请上传品牌LOGO", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    //实现功能：弹窗点击确定 再次进行表单校验 并发送请求
    addOrUpdateTrademark() {
      
      /* validate 是对所有的表单项进行校验
     参数是一个函数 （error，value）=》{} 
     error 如果校验失败 返回false  成功返回true
      validateField是对某个表单进行校验
      resetFields是重置表单 把校验结果和表单内容清空
      */
      this.$refs.form.validate(async (status) => {
        if (status) {
          //校验成功发送请求
          try {
            const { logoUrl, tmName, id } = this.tradeForm;
            if (this.isAddtrademark) {
              await reqAddTrademark(logoUrl, tmName);
            } else {
              await reqUpdateTrademark(id, logoUrl, tmName);
            }
            this.$message.success(
              `${this.isAddtrademark ? "添加" : "修改"}商品成功`
            );
            this.getTrademark(this.currentPage, this.pageSize);
            this.dialogVisible = false;
          } catch (error) {
            this.$message.error(error.message || "未知错误");
          } 
        }
      });
    },
    //点击删除把整条数据干掉
    delTrademark(row) {
      this.$confirm(
        `您确定要删除<i style='color:red'>${row.tmName}</i>品牌数据吗`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          dangerouslyUseHTMLString: true,
          type: "warning",
        }
      ).then(async () => {
        const { id } = row;
        await reqDeleteTrademark(id);
        this.$message({
          type: "success",
          message: "删除成功!",
        });
        let { currentPage, pageSize, trademark } = this;
        if (trademark.length === 1) {
          currentPage = currentPage - 1 <= 0 ? 1 : currentPage - 1;
        }
        //重新获取数据
        this.getTrademark(currentPage, pageSize);
        
      });
    },
    //实现修改数据
    showAddOrUpdateTrademark(isAdd, tradeForm = { tmName: "", logoUrl: "" }) {
      //先让表单显示出来
      this.dialogVisible = true;
      //改变视图数据 转换添加还是修改
      this.isAddtrademark = isAdd;
      //为了清空表单的数据 也是为了获取修改中要得到的id
      this.tradeForm = tradeForm;
      if(this.$refs.form){
       this.$refs.form.clearvalidate&&this.$refs.form.clearvalidate();
      }
      //一上来dialog组件没加载 所以导致子组件form没有加载
      //改data数据 用户界面发生变化 变化是异步的 而方法是同步的
    },
    //上传图片成功触发的函数
    handleAvatarSuccess(res, file) {
      if (res.code === 200) {
        this.tradeForm.logoUrl = res.data;
        return;
      }
      this.$message.error("品牌图片上传失败");
    },
    //图片上传之前触发的函数
    beforeAvatarUpload(file) {
      const fileType = ["image/jpeg", "image/jpg", "image/png"];
      const isTypeOk = fileType.indexOf(file.type) > -1;
      //判断图片大小 最大只能是500kb
      const isLt2M = file.size / 1024 < 500;

      if (!isTypeOk) {
        this.$message.error("上传品牌图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传品牌图片大小不能超过 500kb!");
      }
      return isTypeOk && isLt2M;
    },
    //表单验证
    validator(rule, value, callback) {
      if (!value) {
        callback("请输入品牌名称");
        return;
      }
      if (value.length < 2 || value.length > 6) {
        callback("请输入长度在 2 到 8 个字符的品牌名称");
        return;
      }
      //检验成功
      callback();
      /* 一旦callback调用有参数 就是校验失败 callback(error) */
    },
    //分页器切换页数
    handleSizeChange(val) {
      this.pageSize = val;
      this.getTrademark(this.currentPage, this.pageSize);
    },
    //分页器切换当前页码
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getTrademark(this.currentPage, this.pageSize);
    },
    //封装的所有数据的请求函数
    async getTrademark(page, limit) {
      try {
        this.loading = true;
        const res = await reqGetTrademark(page, limit);
        this.trademark = res.data.records;
        this.total = res.data.total;
        
      } catch (error) {
        this.$message.error(error.message);
      }finally{
        this.loading = false;
      }
    },
    /* //增加品牌以及图片
    addTrademark() {
      this.dialogVisible = true;
    }, */
  },
  mounted() {
    //一挂载就调用封装的函数 请求数据回来
    this.getTrademark(this.currentPage, this.pageSize);
  },
};
</script>

<style lang="sass" scoped>
.el-button--primary
  margin: 15px

.el-table td:first-Child
  text-align: center

.el-input__inner
  width: 80%
.brand-input
  width: 250px

.txt-style
  font-size: 12px
  color: #606266
  margin-left: 73px
</style>
